package de.tum.in.eist.poll.adapter;

import java.util.Iterator;
import java.util.List;

import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;

import de.tum.in.eist.poll.controller.LectureController;
import de.tum.in.eist.poll.service.OnDataUpdate;
import de.tum.in.eist.poll.shared.Lecture;
import de.tum.in.eist.poll.shared.Lecturer;
import de.tum.in.eist.poll.shared.Student;
import de.tum.in.eist.poll.shared.User;

/**
 * The UserView shows user Info like the lectures and if they are already rated or should be rated
 * @author sudi
 *
 */
public class UserViewAdapter {
	public FlexTable lectures = new FlexTable();
	LectureController lectureController;
	
	public UserViewAdapter(LectureController lC) {
		lectureController = lC;
	}
	
	/**
	 * add lecture to the view
	 * @param row The Id of the lecture
	 * @param l The lecture
	 * @param user The user to check if it is already rated
	 */
	public void addLecture(int row, Lecture l, User user) {
		if (user instanceof Student) {
			lectures.setWidget(row, 0, new Hyperlink(l.getLectureTitle(), "lecture_"+row));
			if (l.containsStudent((Student)user))
				lectures.setWidget(row, 1, new Label("already rated"));
			else
				lectures.setWidget(row, 1, new Label("please rate this lecture"));
		}
		else if (user instanceof Lecturer) {
			lectures.setWidget(row, 0, new Hyperlink(l.getLectureTitle(), "lecture_"+row));
			lectures.setText(row, 1, "click to see Lecture statistics");
			if (l.isUpdated()) {
				lectures.setText(row, 2, "feedback updated");
				lectures.getCellFormatter().addStyleName(row, 2, "negativeFeedback");
			}
			else
				lectures.setText(row, 2, "no new feedback");
			
		}
	}
	
	public void create() {
		RootPanel.get().add(new HTML("<h1>"+lectureController.getUserController().getUser().getName()+"</h1>"));
		if (lectureController.getUserController().getUser() instanceof Student)
			RootPanel.get().add(new HTML("<div class=\"userType\">Student</div>"));
		else if (lectureController.getUserController().getUser() instanceof Lecturer)
			RootPanel.get().add(new HTML("<div class=\"userType\">Lecturer</div>"));
		
		RootPanel.get().add(new HTML("<h2 style=\"margin-top: 50px\"><u>Lectures</u></h2>"));
		lectures.setStyleName("statistic", true);
		RootPanel.get().add(lectures);
	}
	
	/**
	 * load lectures into the table
	 */
	public void loadLectures() {
		lectureController.fetchLectures(new OnDataUpdate<List<Lecture>>() {

			@Override
			public void onDataUpdate(List<Lecture> lectures) {
				Iterator<Lecture> it = lectures.iterator();
				int i = 0;
				while (it.hasNext()) {
					addLecture(i, it.next(), lectureController.getUserController().getUser());
					i++;
				}
			}
			
		});
	}
}
